package com.sk.leetcode.arithmetic.test1_10;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 给定一个整数数组和一个目标值，找出数组中和为目标值的两个数。
 * 你可以假设每个输入只对应一种答案，且同样的元素不能被重复利用。
 * <p>
 * 示例：
 * 给定 nums = [2, 7, 11, 15], target = 9
 * 因为 nums[0] + nums[1] = 2 + 7 = 9
 * 所以返回 [0, 1]
 */
public class Test1 {

    public static void main(String[] args) {
        int[] nums = {-9,2,7,11,18,15};
        int target = 9;
        int[] result = twoSum(nums, target);
        System.out.println(result[0]+","+result[1]);



        IntIndex intIndex = new IntIndex(1,2);
        IntIndex intIndex1 = new IntIndex(2,2);
        IntIndex intIndex2 = new IntIndex(3,2);
        List<IntIndex> lists = new ArrayList<>();
        lists.add(intIndex);
        lists.add(intIndex);
        lists.add(intIndex1);
        lists.add(intIndex1);
        lists.add(intIndex2);
        lists.add(intIndex2);

        lists.stream().collect(Collectors.groupingBy(IntIndex::getIndex,Collectors.mapping(IntIndex::getValue,Collectors.toList())));


    }

    /**
     * 获得所以组，返回第一组
     *
     * @param nums
     * @param target
     * @return
     */
    private static int[] twoSum(int[] nums, int target) {
        List<int[]> resultList = new ArrayList<>();

        Map<Integer, List<IntIndex>> map = new HashMap();
        if(nums.length > 0) {
            for (int i = 0; i < nums.length; i++) {
                int num = nums[i];
                List<IntIndex> indices = map.get(target - num);
                if(indices != null && indices.size()>0) {
                    int[] result = new int[2];
                    result[0] = indices.remove(0).getIndex();
                    result[1] = i;
                    resultList.add(result);
                    System.out.println(result[0]+","+result[1]);
                }
                if(indices == null ){
                    indices = new ArrayList<>();
                }
                IntIndex intIndex = new IntIndex(i,num);
                indices.add(intIndex);
                map.put(num,indices);
            }
        }
        if(resultList.size()>0){
            return resultList.get(0);
        }
        return new int[0];
    }


}


class IntIndex {
    int value;
    int index;
    public IntIndex(int index,int value){
        this.index = index;
        this.value = value;
    }
    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }
}
